//
//  LSVolumeView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/27.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSVolumeView.h"

@implementation LSVolumeView

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        self.contentMode = UIViewContentModeRedraw;//内容模式为重绘，因为需要多次重复绘制音量表
        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateViewNotice:) name:@"updateMeters" object:nil];
        //self.soundMeters = @[@0,@0,@0,@0,@0,@0,@0,@0,@0,@0];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.contentMode = UIViewContentModeRedraw;//内容模式为重绘，因为需要多次重复绘制音量表
        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateViewNotice:) name:@"updateMeters" object:nil];
        //self.soundMeters = @[@0,@0,@0,@0,@0,@0,@0,@0,@0,@0];
    }
    
    return self;
}

- (void)drawRect:(CGRect)rect {
    
    if (self.soundMeters != nil && self.soundMeters.count > 0) {
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetLineCap(context, kCGLineCapSquare);
        CGContextSetLineJoin(context, kCGLineJoinRound);
        CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:26.0/255 green:211.0/255 blue:206.0/255 alpha:1].CGColor);
        
        CGFloat noVoice = -45; // 该值代表低于-45.0的声音都认为无声音
        CGFloat maxVolume = 55.0; // 该值代表最高声音为55.0
        
        CGContextSetLineWidth(context, 3);
        
        for (NSInteger index = 0; index < self.soundMeters.count; index++) {
            CGFloat item = ((NSNumber*)self.soundMeters[index]).floatValue;
            NSLog(@"音强：%f",item);
            CGFloat barHeight = maxVolume -(item - noVoice);
            
            CGContextMoveToPoint(context, index * 6 + 3 ,self.frame.size.height/2);
            CGContextAddLineToPoint(context, index * 6 + 3 ,(int)barHeight);
            CGContextAddLineToPoint(context, index * 6 + 3 ,self.frame.size.height-(int)barHeight);
            
            NSLog(@"barHeight = %f",barHeight);
        }
        
        CGContextStrokePath(context);
    }
}

- (void)updateViewNotice:(NSNotification*)notice {
    
    self.soundMeters = (NSArray*)notice.object;
    
    [self setNeedsDisplay];
    
}

@end
